#region

using System;
using System.Collections.Generic;
using VeeTileEngine2012;

#endregion

namespace TimeDRODPOF.TDComponents
{
    public class TDCMovementTargetAI : Component
    {
        private readonly TDGame _game;

        public TDCMovementTargetAI(TDGame mGame, TDCMovement mMovementComponent, TDCTarget mTargetComponent, TDCDirection mDirectionComponent, bool mSetsDirection = true)
        {
            _game = mGame;
            MovementComponent = mMovementComponent;
            TargetComponent = mTargetComponent;
            DirectionComponent = mDirectionComponent;
            SetsDirection = mSetsDirection;
            IsPathfinder = true;
            IsObstinate = true;
        }

        public TDCMovement MovementComponent { get; set; }
        public TDCTarget TargetComponent { get; set; }
        public TDCDirection DirectionComponent { get; set; }
        public bool SetsDirection { get; set; }
        public bool IsPathfinder { get; set; }
        public bool IsObstinate { get; set; }

        public override void NextTurn(object mInput)
        {
            base.NextTurn(mInput);

            if (TargetComponent.Target == null) return;

            var nextNode = _game.Pathfinder.GetPathmap(Entity).JumpPointSearch(X, Y, TargetComponent.Target.X, TargetComponent.Target.Y);
            var nextXY = TDCMovement.GetNextXY(Entity, TargetComponent.Target.X, TargetComponent.Target.Y);

            if (IsPathfinder)
            {
                if (nextNode != null)
                {
                    nextXY = TDCMovement.GetNextXY(Entity, nextNode.X, nextNode.Y);

                    if (MovementComponent.IsReverse)
                    {
                        // TO DO
                    }
                }
                else if (!IsObstinate) return;
            }

            if (SetsDirection) DirectionComponent.Direction = !MovementComponent.IsReverse ? TDCDirection.GetDirection(nextXY) : TDCDirection.GetDirection(-nextXY);

            var ignoreEntities = new List<Entity>();
            foreach (var tag in TargetComponent.TargetTags) ignoreEntities.AddRange(Field.GetEntitiesByTag(tag));

            MovementComponent.TargetX = X + nextXY.X;
            MovementComponent.TargetY = Y + nextXY.Y;
            MovementComponent.IgnoreEntities = ignoreEntities;
        }
    }
}